<template lang="pug">
.ovv-app-wai
  MenuContents
  Loading(
    v-if='getLoadImage && isShowLoading',
    @closeLoading='closeLoading',
    pagetype='overview'
  )
  #container.container.overview.theme-app
    Menu
    Effect(v-if='isShowEffect', :effect='isShowEffect')
    .audio-icon(v-if='getMusic', @click='toggleMusic()')
      //- i.iconfont.icon-jingyin(v-if='!isMute')
      //- i.iconfont.icon-music1(v-if='isMute')
      i.iconfont(:class='{ "icon-jingyin": !isMute, "icon-music1": isMute }')

    .start-pic(v-if='getStartPic && isShowPic', @click='hideStartPic(true)')
      .img-box
        img(:src='getStartPic', alt='')

    .ctrl-boxtour(v-if='!is864')
      .icon(
        :class='{ active: isBig }',
        @touchstart='handleZoomIn',
        v-if='!isBig'
      )
        i.iconfont.icon-zuidahua
      .icon(:class='{ active: !isBig }', @touchstart='handleZoomOut', v-else)
        i.iconfont.icon-zuixiaohua
    .ctrl-boxtour(v-if='is864')
      i.el-icon-zoom-in.iconel.mgb1(@click='handleFd()')
      i.el-icon-zoom-out.iconel(@click='handleSx()')

    .ovv-wrap(ref='imgWrap', @touchmove='handleDragPrevent')
      img.ovv-img(
        :src='getOvvImage',
        draggable='false',
        ref='imgHook',
        @touchstart='handleTouchDown',
        @touchmove='handleTouchMove',
        @touchend='handleTouchEnd',
        alt=''
      )
  Option864(
    v-if='is864',
    @reloadMarkers='reloadMarkers',
    @handleTouchDown='handleTouchDown'
  )
  Option(v-if='!is864')
</template>

<script>
import tourviewMixins from '@/mixins/tourview'
import { doubleClick, handleDefPrevent, isWxBrowser } from '@/utils'
import { initHanddrawBgmusic } from '@/utils/audio'
import { Toast } from 'vant'

export default {
  mixins: [tourviewMixins],
  data() {
    return {
      is864: $globalconfig.MODULES.IS_JIAPEI_PROGRAM_OPEN,
      baseLeft: 0,
      baseTop: 0,
      start: [],
      maxScale: 1.5,
      minScale: 0.95,
      isBig: false,
      pageX: null,
      pageY: null,
      initX: null,
      initY: null,
      isSmall: true,
      isTouch: false,
      timer: null,
      isFirst: true,
      position: {},
    }
  },
  watch: {
    ovvData: {
      handler(val) {
        if (val && val.overview_id) {
          // 如果不是微信浏览器
          if (!isWxBrowser()) {
            initHanddrawBgmusic(val.full_bgmusic_url)
          } else {
            // 初始化音频
            // document.addEventListener('WeixinJSBridgeReady', () => {
            //   initHanddrawBgmusic(val.full_bgmusic_url)
            // }, false)
            this.$store.dispatch('getOverviewWXShareData')
          }
          this.$nextTick(() => {
            this.detectOrient()
          })
        }
      },
      immediate: true,
    },
  },
  created() {
    this.vw = document.documentElement.clientWidth
    this.vh = document.documentElement.clientHeight
  },
  mounted() {
    this.img = this.$refs.imgHook

    this.$vgo.on('listenWXLoad', () => {
      initHanddrawBgmusic(this.ovvData.full_bgmusic_url)
    })

    this.$nextTick(() => {
      setTimeout(() => {
        this.loadImage()
      }, 3000)
    })
    // 利用 CSS3 旋转 对根容器逆时针旋转 90 度
    window.onresize = this.detectOrient
  },
  methods: {
    detectOrient() {
      if (!(this.ovvData && this.ovvData.overview_id)) {
        return false
      }
      let $wrapper = document.getElementById('container')
      if (!$wrapper) {
        return false
      }
      let style = ''
      if (this.ovvData.view_type == 0) {
        // 横屏
        style += 'width:' + this.vh + 'px;'
        style += 'height:' + this.vw + 'px;'
        style += '-webkit-transform: rotate(90deg); transform: rotate(90deg);'
        // 注意旋转中点的处理
        style +=
          '-webkit-transform-origin: ' +
          this.vw / 2 +
          'px ' +
          this.vw / 2 +
          'px;'
        style +=
          'transform-origin: ' + this.vw / 2 + 'px ' + this.vw / 2 + 'px;'
      } else {
        // 竖屏
        style += 'width:' + this.vw + 'px;' // 注意旋转后的宽高切换
        style += 'height:' + this.vh + 'px;'
        style += '-webkit-transform: rotate(0); transform: rotate(0);'
        style += '-webkit-transform-origin: 0 0;'
        style += 'transform-origin: 0 0;'
      }
      $wrapper.style.cssText = style
    },
    resizeImage() {
      if (this.ovvData.view_type == 0) {
        // 横屏
        let sw = this.vw * (this.img.width / this.img.height)
        this.img.style.width = sw + 'px'
        this.img.style.height = this.vw + 'px'

        this.baseLeft = parseInt((this.vh - this.img.width) / 2)
        this.baseTop = parseInt((this.vw - this.img.height) / 2)
      } else {
        // 竖屏
        let sw = this.vh * (this.img.width / this.img.height)
        this.img.style.width = sw + 'px'
        this.img.style.height = this.vh + 'px'
        this.baseLeft = parseInt((this.vw - this.img.width) / 2)
        this.baseTop = 0
        console.log(this.baseTop)
      }

      this.img.style.top = this.baseTop + 'px'
      this.img.style.left = this.baseLeft + 'px'

      if (this.isFirst) {
        this.loadMarkers()
        this.isFirst = false
        this.isShow = true
        // 864默认放大
        if (this.is864) {
          this.handleZoomIn()
        }
      }
    },
    toggleZoom(e) {
      if (doubleClick(e)) {
        this.isBig ? this.handleZoomOut() : this.handleZoomIn()
      }
    },
    handleFd() {
      //放大
      this.maxScale = this.maxScale + 0.2
      this.isBig = true
      let imgDim = this.getImageDim()
      let sw = this.maxScale * imgDim.w //放大后的宽
      let stepW = 0,
        num1 = 0
      const move = () => {
        if (this.ovvData.view_type == 0) {
          this.baseLeft = (this.vh - parseInt(this.img.width)) / 2
          this.baseTop = (this.vw - parseInt(this.img.height)) / 2
        } else {
          this.baseLeft = (this.vw - parseInt(this.img.width)) / 2
          this.baseTop = (this.vh - parseInt(this.img.height)) / 2
          console.log(this.vh, '屏幕', this.img.width, '图片')
        }
        if (stepW < sw / 2) {
          stepW += 100
          num1 = stepW - stepW / 8
          this.img.style.height = imgDim.h + num1 + 'px'
          this.img.style.width = 'auto'
          this.img.style.left = this.baseLeft + 'px'
          this.img.style.top = this.baseTop + 'px'
          this.timer = requestAnimationFrame(move)
        } else {
          cancelAnimationFrame(this.timer)
          this.reloadMarkers()
        }
      }
      cancelAnimationFrame(this.timer)
      this.timer = requestAnimationFrame(move)
      this.isSmall = true
    },
    handleSx() {
      //缩小
      if (this.maxScale <= 1.5) {
        return this.$vgo.tip('已经是最小的缩放比例了', 'warning')
      }
      this.maxScale = 1.5
      this.handleZoomOut()
      this.handleZoomIn()
    },
    handleZoomIn() {
      if (this.isBig) return
      this.isBig = true
      let imgDim = this.getImageDim()
      let sw = this.maxScale * imgDim.w
      let stepW = 0,
        num1 = 0
      const move = () => {
        if (this.ovvData.view_type == 0) {
          this.baseLeft = (this.vh - parseInt(this.img.width)) / 2
          this.baseTop = (this.vw - parseInt(this.img.height)) / 2
        } else {
          this.baseLeft = (this.vw - parseInt(this.img.width)) / 2
          this.baseTop = (this.vh - parseInt(this.img.height)) / 2
        }

        if (stepW < sw / 2) {
          stepW += 100
          num1 = stepW - stepW / 8
          this.img.style.height = imgDim.h + num1 + 'px'
          this.img.style.width = 'auto'
          this.img.style.left = this.baseLeft + 'px'
          this.img.style.top = this.baseTop + 'px'
          this.timer = requestAnimationFrame(move)
        } else {
          cancelAnimationFrame(this.timer)
          this.reloadMarkers()
        }
      }
      cancelAnimationFrame(this.timer)
      this.timer = requestAnimationFrame(move)

      this.isSmall = true
    },
    handleZoomOut() {
      if (!this.isSmall) return
      this.isSmall = false
      this.resizeImage()
      this.reloadMarkers()
      this.isBig = false
    },
    reloadMarkers() {

      this.markerList.map(el => {
        this.setMarkerOffset(el.marker, el.param, {
          x: el.param.x,
          y: el.param.y,
        })
      })
    },
    setMarkerOffset(marker, position) {
      localStorage.setItem('marker', JSON.stringify(position))
      let offset = this.getImagePos()
      let l =
        (this.img.width * position.x) / 100 + offset.left - this.pointObj.w / 2
      let t =
        (this.img.height * position.y) / 100 + offset.top - this.pointObj.h / 2

      // 误差5
      marker.style.left = l - 5 + 'px'
      // 误差32
      marker.style.top = t - 32 + 'px'
      this.isFinish = true
    },
    handleTouchDown(e) {
      e.preventDefault()
      let touch = e.touches[0]
      this.mousePosition.isDrag = true
      if (this.ovvData.view_type == 0) {
        // 横屏
        this.mousePosition.x =
          touch.clientX + this.img.offsetTop - Math.abs(this.baseTop)
        this.mousePosition.y =
          touch.clientY - this.img.offsetLeft - Math.abs(this.baseLeft)
      } else {
        // 竖屏
        console.log(this.img.style.height, 'we')
        this.mousePosition.x =
          touch.clientX + this.img.offsetLeft - Math.abs(this.baseLeft)
        this.mousePosition.y =
          touch.clientY - this.img.offsetTop - Math.abs(this.baseTop)
        this.touchstart(e)
      }
    },
    handleTouchMove(e) {
      let touch = e.touches[0]
      if (this.mousePosition.isDrag) {
        let x, y
        if (this.ovvData.view_type == 0) {
          // 横屏
          x = touch.clientX - this.mousePosition.x - Math.abs(this.baseTop)
          y = touch.clientY - this.mousePosition.y - Math.abs(this.baseLeft)
        } else {
          // 竖屏
          // if (this.img.style.height >= '1200px') {
          //   x =
          //     touch.clientX - this.mousePosition.x - Math.abs(this.baseLeft) * 2
          //   y =
          //     touch.clientY - this.mousePosition.y - Math.abs(this.baseTop) * 2
          // }
          x = touch.clientX - this.mousePosition.x - Math.abs(this.baseLeft)
          y = touch.clientY - this.mousePosition.y - Math.abs(this.baseTop)
          this.touchmove(e) //手指操作中
        }

        // 横屏左右拖动
        if (this.baseLeft < 0) {
          // 图片在可视区内
          if (this.ovvData.view_type == 0) {
            // 横屏
            if (y < this.baseLeft * 2) {
              y = this.baseLeft * 2
            } else if (y > 0) {
              y = 0
            }
            this.img.style.left = y + 'px'
          } else {
            // 竖屏
            if (-x < this.baseLeft * 2) {
              x = -this.baseLeft * 2
            } else if (x < 0) {
              x = 0
            }
            this.img.style.left = -x + 'px'
          }
        }
        if (this.baseTop < 0) {
          if (this.ovvData.view_type == 0) {
            // 横屏
            if (-x < this.baseTop * 2) {
              x = -this.baseTop * 2
            } else if (x < 0) {
              x = 0
            }
            this.img.style.top = -x + 'px'
          } else {
            // 竖屏
            if (y < this.baseTop * 2) {
              y = this.baseTop * 2
            } else if (y > 0) {
              y = 0
            }
            this.img.style.top = y + 'px'
          }
        }
        this.mouse.x = x
        this.mouse.y = y
        this.reloadMarkers()
      }
    },
    handleTouchEnd(e) {
      let touch = e.changedTouches[0]
      this.mousePosition.isDrag = false
      this.mousePosition.x = touch.pageX
      this.mousePosition.y = touch.pageY
      this.touchend(e)
    },
    handleDragPrevent(e) {
      handleDefPrevent(e)
    },
    // 双指开始
    touchstart(e) {
      this.pageX = e.targetTouches[0].pageX // 获取双指的x坐标
      this.pageY = e.targetTouches[0].pageY // 获取双指的y坐标
      this.initX = this.img.offsetLeft // 获取img的left
      this.initY = this.img.offsetTop // 获取img的top
      if (e.touches.length >= 2) {
        //判断是否有两个点在屏幕上
        this.start = e.touches //得到第一组两个点
      }
      this.isTouch = true // 开启手指操作
    },
    //双指开始移动
    // 手势操作中
    touchmove(e) {
      let self = this
      let chmapScale = this.img.style.transform.slice(6, -1) // 获取scale值
      e.preventDefault() // 取消事件的默认动作。
      // 移动操作
      if (e.touches.length >= 2 && this.isTouch) {
        let touchMoveX = e.targetTouches[0].pageX // 移动后的left值
        let touchMoveY = e.targetTouches[0].pageY // 移动后的top值
        // 移动后的left值 - 移动前的left值 =  移动的距离
        // 移动的距离 + div左边距 = 拖放后的位置
        this.img.style.left =
          parseInt(touchMoveX) -
          parseInt(this.pageX) +
          parseInt(this.initX) +
          'px'
        this.img.style.top =
          parseInt(touchMoveY) -
          parseInt(this.pageY) +
          parseInt(this.initY) +
          'px'
      }

      // 放大操作 两个点以上，为了不无限放大造成负担，最大2.4倍
      if (e.touches.length >= 2 && this.isTouch && chmapScale < 2.4) {
        var now = e.touches // 获取手指点的参数
        let scale =
          this.getDistance(now[0], now[1]) /
          this.getDistance(this.start[0], this.start[1]) // 调用算法算出偏移量
        // 最大值
        if (scale > 1.1) {
          this.visible = false
          scale = 2
          // 下面是放大动画，
          this.isTouch = false
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.2 + ')'
          }, 50)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.4 + ')'
          }, 100)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.6 + ')'
          }, 140)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.8 + ')'
          }, 180)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 2 + ')'
          }, 220)
        }
        // 最小值
        if (scale < 1) {
          this.visible = true
          // 缩放后回归原位
          this.img.style.left = 0 + 'px'
          this.img.style.top = '38.5vh'
          scale = 1
          // 下面是放大动画
          this.isTouch = false
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.8 + ')'
          }, 50)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.6 + ')'
          }, 100)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.4 + ')'
          }, 140)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1.2 + ')'
          }, 180)
          setTimeout(() => {
            this.img.style.transform = 'scale(' + 1 + ')'
          }, 220)
        }
      }
    },
    //双指结束 避免误触发
    touchend(e) {
      if (this.isTouch) {
        this.isTouch = false
      }
    },
    // 算出数值，勾股定理方法
    getDistance(p1, p2) {
      var x = p2.pageX - p1.pageX
      var y = p2.pageY - p1.pageY
      return Math.sqrt(x * x + y * y)
    },
  },
}
</script>

<style lang="stylus">
@import '../../assets/styles/tourview.styl';

$white = #fff;

.ctrl-boxtour {
  position: absolute;
  right: 12px;
  bottom: 150px;
  z-index: 101;

  .iconel {
    display: block;
    font-size: 32px;
    background-color: rgba(#e4761c, 0.8);
    color: #fff;
    border-radius: 6px;
  }

  .icon {
    width: 30px;
    height: 30px;
    margin-top: 12px;
    border-radius: 4px;
    text-align: center;
    background-color: rgba(#e4761c, 0.8);

    &.active {
      background-color: #909399;
    }

    i.iconfont {
      font-size: 22px;
      color: $white;
    }
  }
}

$vw_base = 375;
$vw_fontsize = 20;

html {
  font-size: 20px;
  font-size: ($vw_fontsize / $vw_base) * 100vw;
}

@media screen and (orientation: landscape) {
  html {
    font-size: 20px;
    font-size: ($vw_fontsize / $vw_base) * 100vh;
  }
}
</style>

